// Pages/product/product.js
import {Product} from "./product-model.js";
import {Cart} from "../cart/cart_model.js";
var product = new Product;
var cart = new Cart;
Page({

  /**
   * 页面的初始数据
   */
  data: {
     id: null,
     productsArray: [1,2,3,4,5,6,7,8,9,10],
     productCount: 1,
     currentTabIndex: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     var id = options.id;
     this.data.id = id;
     this._onloadData();
    
  },
  _onloadData:function(){
     product.getDetailInfo(this.data.id, (res) => {
        var count = cart.getTotalProductCount();
        this.setData({
           product:res,
           totalProductCount: count,
        })
     })
  },
   bindchange:function(event){
      var index = event.detail.value;
      var selectCount = this.data.productsArray[index];
      this.setData({
         productCount:selectCount
      })
   },
   onChangeTabitem:function(event){
      var index = product.getDataSet(event, 'index');
      this.setData({
         currentTabIndex:index  
      });
   },
   onReady:function(){
      wx.setNavigationBarTitle({
         title: '商品祥情',
      })
   },
   // 添加商品的数量到购物车
   onAddProductToCart:function(){
      var templateCart = {};
      var keys = ['id','name','price','main_img_url','price'];
      for(var key in this.data.product){
         if(keys.indexOf(key) >= 0){
            templateCart[key] = this.data.product[key];
         }
      }
      cart.add(templateCart, this.data.productCount);
      //获取缓存在的商品数量
      var count = cart.getTotalProductCount();
      this.setData({
         totalProductCount: count,
      })
   },
   toCarPage:function(){
      wx.switchTab({
         url: '../cart/cart',
      })
   }
})